package middleware

import (
	"gitee.com/csingo/cMiddleware"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"gitee.com/csingo/cCommon"
	"gitee.com/csingo/cHelper"
	"gitee.com/csingo/cLog"

	"gitee.com/csingo/example/config/vars"
)

type RequestLogMiddleware struct{}

func (i *RequestLogMiddleware) MiddlewareName() (app, name string) {
	return "demo", "RequestLogMiddleware"
}

func (i *RequestLogMiddleware) Handler(ctx *gin.Context, params cMiddleware.MiddlewareParams) (err error) {
	// 设置日志级别
	header := ctx.GetHeader(cCommon.XIndex_LogLevel)
	level := logrus.Level(cHelper.ToInt(header))
	if header != "" && level <= 6 {
		cLog.Level(level)
	}
	// 打印请求参数
	cLog.WithContext(ctx, map[string]any{
		"method": ctx.GetString(cCommon.XIndex_RequestMethod),
		"uri":    ctx.GetString(cCommon.XIndex_RequestURI),
		"query":  ctx.GetString(cCommon.XIndex_QueryData),
		"data":   ctx.GetString(cCommon.XIndex_RequestData),
	}).Debugf("接收 %s 请求", ctx.GetString(cCommon.XIndex_RequestType))

	ctx.Next()

	// 打印返回结果
	data, _ := ctx.Get(cCommon.XIndex_ResponseData)
	cLog.WithContext(ctx, map[string]any{
		"code": ctx.GetInt(cCommon.XIndex_ResponseCode),
		"data": data,
	}).Debugf("响应 %s 请求", ctx.GetString(cCommon.XIndex_RequestType))
	// 设置日志级别
	if header != "" && level <= 6 {
		cLog.Level(vars.LogConfig.Level)
	}

	return
}
